package license

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

// BatchLicensePage 处理批量生成License页面的HTTP请求
func BatchLicensePage(c *gin.Context) {
	html := `
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>批量生成 License</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
        }
        .card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            padding: 24px;
            margin-bottom: 24px;
        }
        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 16px;
            border-bottom: 1px solid #e8e8e8;
        }
        .card-title {
            font-size: 20px;
            font-weight: 600;
            margin: 0;
        }
        .btn {
            background: #1890ff;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        .btn:hover {
            background: #40a9ff;
        }
        .btn-primary {
            background: #1890ff;
        }
        .btn-success {
            background: #52c41a;
        }
        .btn-danger {
            background: #ff4d4f;
        }
        .btn-download {
            background: #722ed1;
        }
        .form-group {
            margin-bottom: 16px;
        }
        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
        }
        .required::after {
            content: " *";
            color: red;
        }
        .form-input {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            font-size: 14px;
            box-sizing: border-box;
        }
        .form-input:focus {
            outline: none;
            border-color: #40a9ff;
            box-shadow: 0 0 0 2px rgba(24,144,255,0.2);
        }
        .file-upload {
            position: relative;
            display: inline-block;
            width: 100%;
        }
        .file-upload-input {
            position: absolute;
            left: 0;
            top: 0;
            opacity: 0;
            width: 100%;
            height: 100%;
            cursor: pointer;
        }
        .file-upload-label {
            display: block;
            padding: 8px 12px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            background: #fff;
            text-align: center;
            cursor: pointer;
        }
        .file-upload-label:hover {
            background: #f5f5f5;
        }
        .file-list {
            margin-top: 16px;
        }
        .file-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 12px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            margin-bottom: 8px;
        }
        .file-item-name {
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        .file-item-remove {
            background: #ff4d4f;
            color: white;
            border: none;
            padding: 4px 8px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
        }
        .form-actions {
            text-align: center;
            margin-top: 24px;
        }
        .btn-space {
            margin: 0 10px;
        }
        .verification-result {
            padding: 20px;
            text-align: center;
            border-radius: 4px;
            margin-top: 20px;
        }
        .valid {
            background-color: #f6ffed;
            border: 1px solid #b7eb8f;
            color: #52c41a;
        }
        .invalid {
            background-color: #fff2f0;
            border: 1px solid #ffccc7;
            color: #ff4d4f;
        }
        .info {
            background-color: #e6f7ff;
            border: 1px solid #91d5ff;
            color: #1890ff;
        }
        h3 {
            margin-top: 0;
            margin-bottom: 10px;
        }
        .progress-bar {
            width: 100%;
            height: 20px;
            background-color: #f5f5f5;
            border-radius: 10px;
            overflow: hidden;
            margin: 10px 0;
        }
        .progress-fill {
            height: 100%;
            background-color: #1890ff;
            width: 0%;
            transition: width 0.3s;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>批量生成 License</h1>
            <p>选择多个JSON文件并批量生成License</p>
        </div>
        
        <div class="card">
            <div class="card-header">
                <h2 class="card-title">选择JSON文件</h2>
            </div>
            <form id="batchForm">
                <div class="form-group">
                    <label class="form-label required">选择JSON文件</label>
                    <div class="file-upload">
                        <input type="file" id="fileInput" class="file-upload-input" accept=".json" multiple>
                        <div class="file-upload-label">
                            点击选择文件或拖拽文件到此处（可多选）
                        </div>
                    </div>
                    <div id="fileList" class="file-list"></div>
                </div>
                
                <div class="form-actions">
                    <button type="button" class="btn btn-primary" onclick="generateBatchLicenses()">
                        批量生成License
                    </button>
                    <button type="button" class="btn" onclick="resetForm()">
                        重置
                    </button>
                </div>
            </form>
        </div>
        
        <div class="card">
            <div class="card-header">
                <h2 class="card-title">处理结果</h2>
            </div>
            <div id="processResult">
                <div class="verification-result info">
                    <p>选择文件并点击"批量生成License"按钮开始处理</p>
                </div>
            </div>
            <div class="form-actions">
                <button id="downloadBtn" class="btn btn-download" style="display: none;" onclick="downloadLicenses()">
                    下载所有License
                </button>
            </div>
        </div>
    </div>

    <script>
        let selectedFiles = [];
        let generatedLicenses = [];

        // 文件选择处理
        document.getElementById('fileInput').addEventListener('change', function(e) {
            const files = Array.from(e.target.files);
            if (files.length > 0) {
                // 添加新选择的文件到列表中
                files.forEach(file => {
                    // 检查是否已存在同名文件
                    const exists = selectedFiles.some(f => f.name === file.name);
                    if (!exists) {
                        selectedFiles.push(file);
                    }
                });
                
                // 更新文件列表显示
                updateFileList();
            }
        });

        // 更新文件列表显示
        function updateFileList() {
            const fileList = document.getElementById('fileList');
            
            if (selectedFiles.length === 0) {
                fileList.innerHTML = '';
                return;
            }
            
            let html = '';
            selectedFiles.forEach((file, index) => {
                html += '<div class="file-item">'+
                        '<div class="file-item-name">' + file.name + '</div>'+
                        '<button class="file-item-remove" onclick="removeFile(' + index + ')">移除</button>'+
                        '</div>';
            });
            
            fileList.innerHTML = html;
        }

        // 移除文件
        function removeFile(index) {
            selectedFiles.splice(index, 1);
            updateFileList();
        }

        // 重置表单
        function resetForm() {
            selectedFiles = [];
            document.getElementById('fileInput').value = '';
            updateFileList();
            
            document.getElementById('processResult').innerHTML = 
                '<div class="verification-result info"><p>选择文件并点击"批量生成License"按钮开始处理</p></div>';
            document.getElementById('downloadBtn').style.display = 'none';
            generatedLicenses = [];
        }

        // 批量生成License
        function generateBatchLicenses() {
            if (selectedFiles.length === 0) {
                alert('请至少选择一个JSON文件');
                return;
            }
            
            // 显示处理中状态
            document.getElementById('processResult').innerHTML = 
                '<div class="verification-result info"><p>正在处理中，请稍候...</p><div class="progress-bar"><div class="progress-fill" id="progressFill"></div></div></div>';
            
            // 重置进度条
            document.getElementById('progressFill').style.width = '0%';
            document.getElementById('downloadBtn').style.display = 'none';
            generatedLicenses = [];
            
            // 逐个处理文件
            processFilesSequentially(0);
        }

        // 逐个处理文件
        function processFilesSequentially(index) {
            if (index >= selectedFiles.length) {
                // 所有文件处理完成
                finishProcessing();
                return;
            }
            
            const file = selectedFiles[index];
            
            // 更新进度条
            const progress = ((index / selectedFiles.length) * 100).toFixed(2);
            document.getElementById('progressFill').style.width = progress + '%';
            
            const reader = new FileReader();
            reader.onload = function(e) {
                try {
                    const jsonData = JSON.parse(e.target.result);
                    
                    // 验证必要字段
                    if (!jsonData.cpuId || !jsonData.cpuName || !jsonData.macAddress || !jsonData.expiryDate) {
                        throw new Error('缺少必要字段');
                    }
                    
                    // 构造请求数据
                    const requestData = {
                        cpuId: jsonData.cpuId,
                        cpuName: jsonData.cpuName,
                        macAddress: jsonData.macAddress,
                        publicIp: jsonData.publicIp || '',
                        expiryDate: jsonData.expiryDate,
                        admin: jsonData.admin || false
                    };
                    
                    // 发送生成License请求
                    fetch('/api/license/generate', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify(requestData)
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.status === 200) {
                            // 保存生成的License
                            generatedLicenses.push({
                                filename: file.name.replace('.json', '_license.json'),
                                data: JSON.stringify(data.data, null, 2)
                            });
                            
                            // 继续处理下一个文件
                            processFilesSequentially(index + 1);
                        } else {
                            throw new Error(data.message || '生成License失败');
                        }
                    })
                    .catch(error => {
                        throw error;
                    });
                } catch (error) {
                    document.getElementById('processResult').innerHTML = 
                        '<div class="verification-result invalid"><h3>处理失败</h3><p>文件: ' + file.name + '</p><p>错误: ' + error.message + '</p></div>';
                }
            };
            
            reader.onerror = function() {
                document.getElementById('processResult').innerHTML = 
                    '<div class="verification-result invalid"><h3>处理失败</h3><p>文件: ' + file.name + '</p><p>错误: 读取文件失败</p></div>';
            };
            
            reader.readAsText(file);
        }

        // 完成处理
        function finishProcessing() {
            // 更新进度条到100%
            document.getElementById('progressFill').style.width = '100%';
            
            if (generatedLicenses.length > 0) {
                document.getElementById('processResult').innerHTML = 
                    '<div class="verification-result valid"><h3>处理完成</h3><p>成功生成 ' + generatedLicenses.length + ' 个License</p></div>';
                document.getElementById('downloadBtn').style.display = 'inline-block';
            } else {
                document.getElementById('processResult').innerHTML = 
                    '<div class="verification-result invalid"><h3>处理完成</h3><p>没有成功生成任何License</p></div>';
            }
        }

        // 下载所有License
        function downloadLicenses() {
            if (generatedLicenses.length === 0) {
                alert('没有可下载的License');
                return;
            }
            
            // 创建一个ZIP文件
            const zip = new JSZip();
            
            // 添加所有License文件到ZIP
            generatedLicenses.forEach(license => {
                zip.file(license.filename, license.data);
            });
            
            // 生成ZIP文件并下载
            zip.generateAsync({type:"blob"})
            .then(function(content) {
                const url = URL.createObjectURL(content);
                const a = document.createElement('a');
                a.href = url;
                a.download = 'licenses.zip';
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
            });
        }

        // 拖拽上传功能
        const dropArea = document.querySelector('.file-upload');
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            dropArea.addEventListener(eventName, preventDefaults, false);
        });

        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }

        ['dragenter', 'dragover'].forEach(eventName => {
            dropArea.addEventListener(eventName, highlight, false);
        });

        ['dragleave', 'drop'].forEach(eventName => {
            dropArea.addEventListener(eventName, unhighlight, false);
        });

        function highlight() {
            dropArea.querySelector('.file-upload-label').style.backgroundColor = '#e6f7ff';
            dropArea.querySelector('.file-upload-label').style.borderColor = '#1890ff';
        }

        function unhighlight() {
            dropArea.querySelector('.file-upload-label').style.backgroundColor = '#fff';
            dropArea.querySelector('.file-upload-label').style.borderColor = '#d9d9d9';
        }

        dropArea.addEventListener('drop', handleDrop, false);

        function handleDrop(e) {
            const dt = e.dataTransfer;
            const files = dt.files;
            if (files.length) {
                // 添加拖拽的文件到列表中
                Array.from(files).forEach(file => {
                    if (file.name.endsWith('.json')) {
                        // 检查是否已存在同名文件
                        const exists = selectedFiles.some(f => f.name === file.name);
                        if (!exists) {
                            selectedFiles.push(file);
                        }
                    }
                });
                
                // 更新文件列表显示
                updateFileList();
            }
        }
    </script>
    
    <!-- 引入JSZip库用于生成ZIP文件 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
</body>
</html>
`
	c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(html))
}